import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, //基础地址
  timeout: 70000,
}); //创建一个axios实例

//请求拦截器
service.interceptors.request.use(
  (config) => {
    //注入token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data instanceof Blob) return response.data;
    const { data, success, message } = response.data;
    if (success) {
      return data;
    } else {
      Message({ type: "error", message: "用户名或密码错误" });
      return Promise.reject(message);
    }
  },
  async (error) => {
    if (error.response.status === 401) {
      await store.dispatch("user/logout");
      router.push("/login");
    }
    Message({ type: "error", message: error.message || "请求失败" });
    // debugger;

    return Promise.reject(error);
  }
);

export default service;
